package com.blackink.service.impl;

import com.blackink.mapper.UserMapper;
import com.blackink.pojo.User;
import com.blackink.service.UserService;
import com.blackink.tool.RandomString;
import com.blackink.tool.UpdateException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.Subject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }

    @Override
    public List<User> queryUserList(String userName, String phone, String start, String end) {
        return userMapper.queryUserList(userName,phone,start,end);
    }

    @Override
    @Transactional
    public Integer[] addUser(User user,Integer roleId) {
        Integer[] i = new Integer[3];
        List<User> list = userMapper.queryUser(user.getLoginName());
        if (list.size()>=1){
            i[0]= -1;
            return i;
        }else {
            i[0]=0;
        }
        Date date = new Date();
        user.setCreateTime(date);
        String salt = RandomString.getRandomSalt();
        user.setPassword(new SimpleHash("md5",user.getPassword(),salt,1).toString());
        user.setSalt(salt);
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        if (loginUser != null ){
            user.setCreateBy(loginUser.getId());
        }else {
            user.setCreateBy(1);
        }
        Integer ui = userMapper.addUser(user);
        Integer uri = userMapper.addUserRole(user,roleId);
        i[1] = ui;
        i[2] = uri;
        return i;
    }

    @Override
    public void loginUpdate(String username, String ipAddr) throws UpdateException {
        Integer id = userMapper.queryUserByName(username).getId();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Integer num = userMapper.loginUpdate(id,ipAddr,dateFormat.format(date));
        if (num==0){
            throw new UpdateException("登录遇到些问题，请重试");
        }
    }
}
